#include <assert.h>
#include "network.h"

#define BASE_NETWORK ((IPAddress)0x0000a8c0)  /* 192.168.0.x */
#define NETMASK ((IPAddress)0x00FFFFFF) /* 255.255.255.0 , i.e. /24 */

#define MAX_ADDR 255

IPAddress network_local_address(void) {
    assert (nodeinfo.address < MAX_ADDR);
    return ((IPAddress)BASE_NETWORK+((IPAddress)(nodeinfo.address)<<24));
}

bool network_is_valid(IPAddress ipaddr) {
    return ((ipaddr & NETMASK) == BASE_NETWORK);
}

int network_read_network(IPAddress *destaddr, void *message, size_t *length) {
    CnetAddr real_destination;
    int result = 0;

    result = CNET_read_application(&real_destination, message, length);
    
    if (result==0) {
        assert(0 < real_destination && real_destination <= MAX_ADDR);
        *destaddr = ((IPAddress)BASE_NETWORK+((IPAddress)(real_destination)<<24));
        assert (network_is_valid(*destaddr));
    }
    
    return result;
}

int network_write_network(void *message, size_t *length) {
    return CNET_write_application(message, length);
}
	    
int network_pause_destination(IPAddress destaddr) {
    assert (network_is_valid(destaddr));
    return CNET_disable_application((destaddr & NETMASK) >> 24);
}
 
int network_unpause_destination(IPAddress destaddr) {
    assert (network_is_valid(destaddr));
    return CNET_enable_application((destaddr & NETMASK) >> 24);
}

const char *network_display_address(IPAddress ipaddr) {
#define RESULTSIZE 30
    static char result[RESULTSIZE];
    snprintf(result, RESULTSIZE, "%d.%d.%d.%d",
        ipaddr & 0xff,
        (ipaddr >> 8) & 0xff,
        (ipaddr >> 16) & 0xff,
        (ipaddr >> 24) & 0xff
        );
    result[RESULTSIZE] = '\0';
    return result;
}

